//
//  ViewController.swift
//  3DTouch
//
//  Created by yaqiang bi on 2017/5/19.
//  Copyright © 2017年 yaqiang bi. All rights reserved.
//

import UIKit

class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UIViewControllerPreviewingDelegate{
    let cellID = "cellID"
    
    
    private var mainCollectionView:UICollectionView!
    override func viewDidLoad() {
        super.viewDidLoad()
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: 100, height: 100)
        flowLayout.minimumLineSpacing = 5.0
        flowLayout.minimumInteritemSpacing = 5.0
        flowLayout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20)
        
        self.mainCollectionView = UICollectionView(frame: CGRect.init(x: 0, y: 20, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height-20), collectionViewLayout: flowLayout)
        self.mainCollectionView.backgroundColor = UIColor.white
        self.mainCollectionView.delegate = self
        self.mainCollectionView.dataSource = self
        self.mainCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellID)
        self.view.addSubview(self.mainCollectionView)
        
        self.registerForPreviewing(with: self, sourceView: self.view)
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath)
        cell.backgroundColor = UIColor.lightGray
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }
    
    //MARK:按压图片进入预览模式
    func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
        let content = ContentViewController()
        
        let index = self.mainCollectionView.indexPathForItem(at: CGPoint.init(x: location.x, y: location.y-10+self.mainCollectionView.contentOffset.y))
        if index == nil {
            return nil
        }else{
            content.index = index?.row
            return content
        }
    }
    
    func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
        self.show(viewControllerToCommit, sender: self)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

